require 'digest/sha1'
class User < ActiveRecord::Base
  has_many :topics
  has_many :comments
  validates_presence_of    :account
  validates_uniqueness_of  :account
  validates_presence_of    :password
  validates_confirmation_of :password ,:message=>"需要验证 "
  validates_length_of       :password ,:minimum=> 6,:too_short=>"您输入的密码长度少于6位"
  validates_presence_of    :e_mail
  validates_format_of :e_mail, :with => /^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i,
    :on => :create ,:message=>"is not a valid email address"
  attr_accessor  :password_confirmation
  validates_confirmation_of :password

   validate  :password_non_blank
  def self.authenticate(account,password)
      user=self.find_by_account(account)
      if user
        expected_password = encrypted_password(password,user.salt)
        if user.hashed_password != expected_password
          user = nil
        end
      end
      user
    end


    def password
      @password
    end


    def password=(pwd)
      @password=pwd
      return if pwd.blank?
      create_new_salt
      self.hashed_password = User.encrypted_password(self.password, self.salt)
    end

  private

    def password_non_blank
      errors.add(:password, "Missing password") if hashed_password.blank?
    end



    def create_new_salt
      self.salt = self.object_id.to_s + rand.to_s
    end

    def self.encrypted_password(password,salt)
      string_to_hash = password + "db" + salt
      Digest::SHA1.hexdigest(string_to_hash)
    end
end
